import { ModalTypes, ModalClassName } from './typing.js';

/**
 * 工厂模式 通过传入的状态 来自动实例化相应的类
 * 
 * 父类 有公共的方法 \ 熟悉 \ 静态工具
 * 
 * 子类 对每种状态内部属性(功能)进行加工(扩展)
 */

class Modal {
  constructor(status) {
    this.status = status;
  }

  get className() {
    let classStr = 'modal';
    switch (this.status) {
      case ModalTypes.SUCCESS:
        classStr += ` ${ModalClassName.SUCCESS}`;
        break;
      case ModalTypes.WARNING:
        classStr += ` ${ModalClassName.WARNING}`;
        break;
      case ModalTypes.ERROR:
        classStr += ` ${ModalClassName.ERROR}`;
        break;
      default:
        break;
    }
    return classStr;
  }

  static checkStatusIsExist(types, status) { // 工具函数一般为静态方法
    for (let k in types) {
      if (types[k] === status) return true;
    }

    return false;
  }

  static outputInfo(info) {
    console.log(info);
  }
}

class SuccessModal extends Modal {
  constructor(title) {
    super(ModalTypes.SUCCESS);
    this.title = '成功:' + title;
  }

  // 可以进行不同的扩展
  navToURL(url) {
    window.location.href = url;
  }
}

class WarningModal extends Modal {
  constructor(title) {
    super(ModalTypes.WARNING);
    this.title = '警告:' + title;
  }

  outputInfo(info) {
    Modal.outputInfo('警告: ' + info);
  }
}

class ErrorModal extends Modal {
  constructor(title) {
    super(ModalTypes.ERROR);
    this.title = '失败:' + title;
  }

  outputInfo(err) {
    Modal.outputInfo('错误: ' + err);
  }
}

class ModalFactory {
  constructor (dom) {
    this.dom = dom;
  }

  create(title, status) {
    const statusIsExist = Modal.checkStatusIsExist(ModalTypes, status);

    if (!statusIsExist) {
      throw new Error('Modal type is incorrect');
    }

    const dom = this.dom;
    let modal = null;

    switch (status) {
      case ModalTypes.SUCCESS:
        modal = new SuccessModal(title);
        break;
      case ModalTypes.WARNING:
        modal = new WarningModal(title);
        break;
      case ModalTypes.ERROR:
        modal = new ErrorModal(title);
        break;
      default:
        break;
    }

    dom.getElementsByTagName('header')[0].innerText = modal.title;
    dom.className = modal.className;

    return {
      outputInfo: modal.outputInfo,
      navToURL: modal.navToURL
    }
  }
}

export default ModalFactory;